"""
user_id = auth.user.id if auth.is_logged_in() else 0
auth.user_id = user_id

db.define_table('jobs',
                Field('job_name','string'),
                Field('submitted_by',db.auth_user,default=user_id,writable=False,readable=False),
                Field('submitted_time','datetime',default=request.now,writable=False,readable=False),
                Field('job_id','string',writable=False,readable=False),
                Field('status','string',default='ready',writable=False,readable=False),
                Field('script','upload',autodelete=True),
                Field('stdout','upload',writable=False,readable=False,autodelete=True),
                Field('stderr','upload',writable=False,readable=False,autodelete=True)
)

db.jobs.script.requires=IS_NOT_EMPTY()
db.jobs.job_name.requires=IS_NOT_EMPTY()
db.jobs.status.requires=IS_IN_SET(('ready','running', 'complete'))
"""
######################################
# this stores pbs jobs!
######################################

db.define_table('job',
                Field('job_name','string'),
                Field('submitted_by',db.auth_user,default=auth.user_id),
                Field('submitted_on','datetime',default=request.now),
                Field('job_id','string'),
                Field('status','string',default=QUEUED),
                Field('script','upload',autodelete=True),
                Field('stdin','upload',autodelete=True),
                Field('stdout','upload',autodelete=True),
                Field('stderr','upload',autodelete=True))

db.job.script.requires=IS_NOT_EMPTY()
db.job.job_name.requires=IS_NOT_EMPTY()
db.job.status.requires=IS_IN_SET((QUEUED, PROCESSING, COMPLETED)) #FAILED unused

def fixname(name):
    return name[name.rfind('/')+1:]

db.job.id.represent=lambda id:SPAN(SPAN(id,_class="id0"),INPUT(_type='checkbox',_name='delete_%s'%id,_id='delete_%s'%id))
db.job.script.represent=lambda name: A('file',_href=URL(r=request,c='pbs',f='show',args=name)) if name else ''
db.job.stdin.represent=lambda name: A('file',_href=URL(r=request,c='pbs',f='show',args=fixname(name))) if name else ''
db.job.stdout.represent=lambda name: A('file',_href=URL(r=request,c='pbs',f='show',args=fixname(name))) if name else ''
db.job.stderr.represent=lambda name: A('file',_href=URL(r=request,c='pbs',f='show',args=fixname(name))) if name else ''

#
# pbs scripts, .out, .err files go in this folder
# create it if it does not exist
#


def submit_job(script,id,user_id=None):
    """
    if script is 'plaquette.py' id is a configfile.id
    if script is 'algorithm.py' id is a processedfile.id
    if script is 'visualize.py' id is a visualizedfile.id
    """
    raw_script_filename = locate_file('process_script_%s' % id)
    script_file = open(raw_script_filename, 'wb')
    script_file.write('#!/bin/bash\n')
    script_file.write('HOME=%s MPLCONFIGDIR=%s WEB2PY_ROOT=%s python -u %s -S vis -M -N -R %s %s\n' %
                      (os.getenv('HOME'),
                       request.folder,
                       os.getcwd(),
                       os.path.join(os.getcwd(), 'web2py.py'),
                       os.path.join(request.folder,'private',script),
                       id))
    script_file.close()
    script_file = open(raw_script_filename, 'rb')
    if user_id:
        db.job.insert(submitted_by=user_id,job_name='process job for %s %s' % (script,id),
                      script=db.job.script.store(script_file, 'process_script_%s' % id))
    else:
        db.job.insert(job_name='process job for %s %s' % (script,id),
                      script=db.job.script.store(script_file, 'process_script_%s' % id))
    os.unlink(raw_script_filename)
